/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.upf.Ilusio.Learning;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.util.Date;
import java.util.Iterator;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.muc.MultiUserChat;

//packet listener will required you to implement a method
//called "processPacket(Packet packet)" which lets you
//go lower level to handle the in/out packets better
final public class P2PClient extends JFrame implements ActionListener, PacketListener {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private JButton btnLogin,  btnSend,  btnQuit;
    private JTextArea taChatArea;
    private JTextField tfChatMessage,  tfTargetResource,  tfLoginName,  tfResourceName;
    private JComboBox cbOpponent;
    private JPasswordField pfLoginPassword;
// GoogleTalkConnection is one of the class by Smack
    private XMPPConnection con = null;
// GroupChat will allowed you to listen to more than 1 opponent
    private MultiUserChat chat = null;
    private String login_name = "";
// private String login_password = "";
    private String opponent = "";
    private boolean isLogin = false;
// require class -- PacketFilter and PacketCollector, explain below
    private PacketFilter filter = null;
// Message is a class to hold all data which extracted from the packet,
// e.g. sender, receiver, timestamp, message ... etc
// private Message msg = null;
    public P2PClient() {
        super("Chat Client");
        setSize(400, 300);
        setResizable(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout(0, 0));
        initComponents();
        setVisible(true);
    }

    public void initComponents() {
        btnLogin = new JButton("Login");
        btnLogin.addActionListener(this);
        btnSend = new JButton("Send");
        btnSend.setMnemonic(KeyEvent.VK_ENTER);
        btnSend.addActionListener(this);
        btnQuit = new JButton("Quit");
        btnQuit.addActionListener(this);
        taChatArea = new JTextArea(10, 40);
        taChatArea.setEditable(false);
        JScrollPane chatScroller = new JScrollPane(taChatArea);
        chatScroller.setPreferredSize(new Dimension(300, 200));
        chatScroller.setMinimumSize(new Dimension(300, 200));
        chatScroller.setAlignmentX(Component.LEFT_ALIGNMENT);
        tfChatMessage = new JTextField(40);
        tfTargetResource = new JTextField(40);
        tfTargetResource.setText("Home");
        tfLoginName = new JTextField(10);
        tfResourceName = new JTextField(10);
        tfResourceName.setText("Home");
        cbOpponent = new JComboBox();
        cbOpponent.setEditable(true);
        pfLoginPassword = new JPasswordField(10);
        JPanel pnlButton = new JPanel(new GridLayout(2, 1, 0, 0));
        JPanel pnlLogin = new JPanel(new GridLayout(4, 2, 0, 0));
        JPanel pnlMessage = new JPanel(new GridLayout(3, 1, 0, 0));
        pnlLogin.add(new JLabel("User Name:"));
        pnlLogin.add(tfLoginName);
        pnlLogin.add(new JLabel("Resource:"));
        pnlLogin.add(tfResourceName);
        pnlLogin.add(new JLabel("Password:"));
        pnlLogin.add(pfLoginPassword);
        pnlLogin.add(new JLabel("press here to login ->"));
        pnlLogin.add(btnLogin);
        pnlButton.add(btnSend);
        pnlButton.add(btnQuit);
        pnlMessage.add(cbOpponent);
        pnlMessage.add(tfChatMessage);
        pnlMessage.add(tfTargetResource);
        setChat(false);
        add(pnlLogin, BorderLayout.NORTH);
        add(pnlButton, BorderLayout.EAST);
        add(chatScroller, BorderLayout.CENTER);
        add(pnlMessage, BorderLayout.SOUTH);
    }
// disable sending meassage when variable 'mark' is false (offline), and
// vice-versa
    public void setChat(boolean mark) {
        tfChatMessage.setEnabled(mark);
        tfTargetResource.setEnabled(mark);
        cbOpponent.setEnabled(mark);
        btnSend.setEnabled(mark);
    }
// clean up jobs appoint exit
    public void logout() {
        if (con != null) {
            con.disconnect();
        }
        cbOpponent.removeAllItems();
    }
// when user logged in, set the flag to true (online)
    public boolean login(final String aLogin, final String aPassword,
            String resource) {
// get textfield's username
        this.login_name = aLogin;
// get passwordfield's password
        boolean flag = false;
        try {
// con = new GoogleTalkConnection();
            ConnectionConfiguration config = new ConnectionConfiguration(
                    "talk.google.com", 5222, "gmail.com");
            
            config.setSASLAuthenticationEnabled(true);
            config.setReconnectionAllowed(true);
            con = new XMPPConnection(config);
            con.connect();
            con.login(aLogin, aPassword, resource);
            System.out.println(con.getUser());
            
// filter the XML packet into a PacketCollector (much like a queue),
// so that you can get them back later
// filter = new AndFilter(new PacketTypeFilter(Message.class),new
// NotFilter(new FromContainsFilter(con.getUser())));
// filter = new PacketTypeFilter(Message.class);
            //filter = new AndFilter(new PacketTypeFilter(Message.class), new NotFilter(new FromContainsFilter(con.getUser())));
            filter = new AndFilter(new PacketTypeFilter(Message.class), new PacketIDFilter("IlusioV1b"));
            con.createPacketCollector(filter);
// initialise your chatgroup
            chat = new MultiUserChat(con, aLogin + "'s Chat");

// chat = con.createGroupChat(login_name + "'s Chat");
// initialise your message
// get all user from your friends list
            Roster roster = con.getRoster();
            for (Iterator<RosterEntry> i = roster.getEntries().iterator(); i.hasNext();) {
                RosterEntry re = (RosterEntry) i.next();
                cbOpponent.addItem(re.getUser());
//                if(re.getUser().equalsIgnoreCase("xday666@gmail.com")){
//                    //roster.
                    
                //}
// Register the listener.
            }
            cbOpponent.addItem(con.getUser());
            con.addPacketListener(this, filter);
            setChat(true);
            flag = true;
        } catch (Throwable ex) {
            ex.printStackTrace();
// any thing during login, disable user to send message
            setChat(false);
            flag = false;
        }
        return flag;
    }

    public void windowClosing(WindowEvent we) {
        logout();
    }
// implementing processPacket for PacketListener interface
    public void processPacket(Packet packet) {
// Put the incoming message on the chat history or chat board.
        if (packet instanceof Message) {
            Message msg = (Message) packet;
            Date date = (Date) msg.getProperty("fecha");
            taChatArea.append(date + ":FROM-->" + msg.getFrom() + ":TO-->" + msg.getTo() + ":BODY-->" + msg.getBody() + "\n");
        }
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnLogin) {
            String test = btnLogin.getText();
            if (test.equals("Login")) {
                isLogin = login(tfLoginName.getText().toString().trim(),
                        new String(pfLoginPassword.getPassword()).trim(),
                        tfResourceName.getText().toString().trim());
                btnLogin.setText("Logout");

                //Cambiar mi status
                Presence presence = new Presence(Presence.Type.available);
                presence.setStatus("IlusioV2b");
                con.sendPacket(presence);

                String hola = "ddfgdfg";
                hola.getBytes();

            } else if (test.equals("Logout")) {
                logout();
                setChat(false);
                isLogin = false;
                btnLogin.setText("Login");
            }
        } else if (e.getSource() == btnSend) {
            opponent = cbOpponent.getSelectedItem().toString();
            String content = tfChatMessage.getText().toString();
            if (isLogin) {
                try {
                    Message msg = new Message();
                    System.out.println("TO:" + opponent + "/" + tfTargetResource.getText().toString());
                    
                    msg.setTo(opponent + "/" + tfTargetResource.getText().toString());


                    //Descubrir status
                    Roster roster = con.getRoster();
                    Presence p = roster.getPresence(opponent);
                    System.out.println(opponent + "-" + p.getStatus());
// msg.setTo(opponent);
// msg.setTo("fotos.bandaroquetes");
// msg.setTo(opponent);
                    msg.setPacketID("IlusioV1b");
                    System.out.println(tfTargetResource.getText().toString());
                    msg.setBody(content);
                    msg.setProperty("fecha", new Date());
                    chat.sendMessage(msg);
// append your sent message to chat board
                    taChatArea.append(login_name + ": " + tfChatMessage.getText() + "\n");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } else if (e.getSource() == btnQuit) {
            logout();
            System.exit(0);
        }
    }

    public static void main(String[] args) {
        new P2PClient();
    }
}

/**
 *
 * @author xday666
 */
